package com.weiaibenpao.demo.chislim.ui;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.Window;
import android.widget.ImageView;
import android.widget.Toast;

import com.jaeger.library.StatusBarUtil;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.RunningPreferences;
import com.weiaibenpao.demo.chislim.RunningService;
import com.weiaibenpao.demo.chislim.bean.UserBean;
import com.weiaibenpao.demo.chislim.util.SharedPrefsUtil;
import com.weiaibenpao.demo.chislim.util.Utils;
import com.weiaibenpao.demo.chislim.util.WriteReadSharedPrefs;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.weiaibenpao.demo.chislim.util.Default.REQUEST_PERMISSION_CODE;

public class LeadActivity extends Activity {

    @BindView(R.id.mySport)
    ImageView mySport;
    //用户信息
    private UserBean user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_lead);
        StatusBarUtil.setColor(this , getResources().getColor(R.color.ku_bg ) , 0);
        ButterKnife.bind(this);
        CheckPerMission();
        handler.postDelayed(new SplashRunnable(), 1000);//设置3秒钟延迟执行splashhandler线程。其实你这里可以再新建一个线程去执行初始化工作，如判断SD,网络状态等
        user = UserBean.getUserBean();
        if(!Utils.isNetWorkConnected()) Toast.makeText(this, "亲，网络连了么？", Toast.LENGTH_LONG).show();
//        Picasso.with(this).load(R.drawable.welcomeimage).into(mySport);
    }

    private class SplashRunnable implements Runnable {
        public void run() {
            getUser();
        }
    }


    public void getUser() {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {

                //如果文件中有用户数据保存，直接进入首页,为true则为用用户信息，false时为没有用户，跳转至登录界面
                if(SharedPrefsUtil.getValue(LeadActivity.this.getApplicationContext(),WriteReadSharedPrefs.PREFS_NAME,"content",false)){
                    WriteReadSharedPrefs.readUser(LeadActivity.this.getApplicationContext(),user);

                    Message msg = new Message();

                    msg.arg1 = 1;

                    handler.sendMessage(msg);

                } else {
                    Message msg = new Message();

                    msg.arg1 = 0;

                    handler.sendMessage(msg);

                }
//            }
//        }).start();
    }

   private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            Intent intent;
            switch (msg.arg1) {
                case 1:                  //跳转至首页
                    intent = new Intent(LeadActivity.this, MainActivity.class);
                    startActivity(intent);
                    int state = RunningPreferences.getInstance().getRunningState();
                    if(RunningService.RUNNING == state || RunningService.PAUSE == state){
                        Intent serviceIntent = new Intent(LeadActivity.this, RunningService.class);
                        serviceIntent.putExtra(RunningService.RUNNING_ACTIVITY,RunningPreferences.getInstance().getRunningActivity());
                        startService(serviceIntent);
//                        Log.e("LeadActivity","runningActivity is "+RunningPreferences.getInstance().getRunningActivity());
                    }
                    LeadActivity.this.finish();
                    break;
                case 0:                 //跳转至登录界面
                    intent = new Intent(LeadActivity.this, LoginActivity.class);
                    startActivity(intent);
                    LeadActivity.this.finish();
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        Log.e("LeadActivity","onDestroy");
        handler.removeCallbacksAndMessages(null);
    }

    /**
     * 6.0的权限监测
     */
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,};

    /**
     * 权限检查
     * @param
     */
    public void CheckPerMission(){
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this,PERMISSIONS_STORAGE,
                    REQUEST_PERMISSION_CODE);
        }
    }

    /**
     * 权限申请的回调
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        doNext(requestCode,grantResults);
    }

    /**
     * 权限的处理
     * @param requestCode
     * @param grantResults
     */
    private void doNext(int requestCode, int[] grantResults) {
        if (requestCode == REQUEST_PERMISSION_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted     同意

            } else {
                // Permission Denied       拒绝
                new AlertDialog.Builder(LeadActivity.this)
                        .setTitle("权限申请")
                        .setMessage("在设置-应用-权限中开始读写权限，以保证功能的正常使用")
                        .setPositiveButton("去开启", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                Uri uri = Uri.fromParts("package", getPackageName(), null);
                                intent.setData(uri);
                                startActivity(intent);

                                dialog.dismiss();
                            }
                        })
                        .setNegativeButton("取消", null)
                        .setCancelable(false)
                        .show();
            }
        }
    }
}
